import gdb
import logging

'''
cd /path/to/kernel-build
gdb -q vmlinux      # can NOT use gdb -x/--command this_file
(gdb) source /path/to/this_file
'''

def _exec(cmd:str, to_string=True):
    print(f"cmd: {cmd}")
    return gdb.execute(cmd, to_string=to_string)

def get_sec_start(buf, sec) -> int:
    pos = buf.find(f"is {sec}")
    if pos < 0:
        return 0xdeadbeef
    tmp = buf[:pos].rfind('\n')
    if tmp < 0:
        return 0xdeadbeef
    addr = buf[tmp:pos].split()[0]
    return int(addr, 16)

# _exec('file vmlinux')

# buf = _exec("info files")
buf = _exec("info target")
head_text_addr = get_sec_start(buf, ".head.text")
text_addr = get_sec_start(buf, ".text")
init_text_addr = get_sec_start(buf, ".init.text")

qemu_head_text_addr = 0x40200000
qemu_text_addr = qemu_head_text_addr + text_addr - head_text_addr
qemu_init_text_addr = qemu_head_text_addr + init_text_addr - head_text_addr

print(".head.text 0x{:016X} 0x{:X}".format(head_text_addr, qemu_head_text_addr))
print(".text      0x{:016X} 0x{:X}".format(text_addr, qemu_text_addr))
print(".init.text 0x{:016X} 0x{:X}".format(init_text_addr, qemu_init_text_addr))

_exec(f"add-symbol-file vmlinux -s .head.text 0x{qemu_head_text_addr:X}")
_exec(f"add-symbol-file vmlinux -s .text      0x{qemu_text_addr:X}")
_exec(f"add-symbol-file vmlinux -s .init.text 0x{qemu_init_text_addr:X}")
